from PIL import Image
import os

def merge_images(folder1, folder2, output_folder):
    os.makedirs(output_folder, exist_ok=True)

    # 获取两个文件夹的所有文件
    files1 = os.listdir(folder1)
    files2 = os.listdir(folder2)

    # 建立文件名到路径的映射（去掉后缀）
    def build_name_map(files, folder):
        name_map = {}
        for f in files:
            name, ext = os.path.splitext(f)
            name_map[name] = os.path.join(folder, f)
        return name_map

    map1 = build_name_map(files1, folder1)
    map2 = build_name_map(files2, folder2)

    # 找到公共文件名
    common_names = set(map1.keys()) & set(map2.keys())

    for name in common_names:
        path1 = map1[name]
        path2 = map2[name]

        # 打开图片
        img1 = Image.open(path1)
        img2 = Image.open(path2)

        # 检查高度是否一致
        if img1.height != img2.height:
            print(f"⚠️ 高度不一致，跳过: {name}")
            continue

        # 创建新图片（宽度 = 两张图片宽度之和，高度不变）
        new_width = img1.width + img2.width
        new_img = Image.new("RGB", (new_width, img1.height))

        # 粘贴图片
        new_img.paste(img1, (0, 0))
        new_img.paste(img2, (img1.width, 0))

        # 保存图片
        output_path = os.path.join(output_folder, f"{name}.jpg")
        new_img.save(output_path)
        print(f"✅ 已生成: {output_path}")


if __name__ == "__main__":
    folder1 = input("请输入第一个图片文件夹路径: ")
    folder2 = input("请输入第二个图片文件夹路径: ")
    output_folder = input("请输入输出文件夹路径: ")
    merge_images(folder1, folder2, output_folder)
